import axios, { type InternalAxiosRequestConfig } from 'axios'

const cacheMap = new Map()
const cacheExpirationTime = 1000 * 60 * 60 // 1小时更新一次

const instance = axios.create({
  baseURL: '',
  withCredentials: false
})

//请求拦截
instance.interceptors.request.use(
  (config) => {
    //获取当前请求的请求标识
    const key = generateRequestKey(config)
    //读取请求缓存
    const requestCache = cacheMap.get(key)
    //缓存存在并且缓存并未过期，返回缓存，否则正常发送请求
    if (requestCache && Date.now() - requestCache.cacheDate < cacheExpirationTime) {
      return Promise.reject({
        cached: true,
        key
      })
    }
    //如果当前请求未被缓存，则正常发送请求
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

//响应拦截
instance.interceptors.response.use(
  (res) => {
    if (res.data.errno === 0) {
      const key = generateRequestKey(res.config, true)
      if (!cacheMap.has(key)) {
        cacheMap.set(key, { cacheDate: Date.now(), res: res })
      } else {
        // 若已存在缓存，并且缓存已过期，则更新缓存
        const requestCache = cacheMap.get(key)
        if (Date.now() - requestCache.cacheDate > cacheExpirationTime) {
          cacheMap.set(key, {
            cacheDate: Date.now(),
            res: res
          })
        }
      }
    }
    return res
  },
  (err) => {
    if (err.cached) {
      //返回缓存
      return Promise.resolve(cacheMap.get(err.key).res)
    } else {
      // 对响应错误做点什么
      return Promise.reject(err)
    }
  }
)

//生成请求标识
function generateRequestKey(config: InternalAxiosRequestConfig, isResponse = false): string {
  let requestKey = config.url ?? ''
  if (isResponse) {
    requestKey += (config.data ?? '') + (JSON.stringify(config.params) ?? '')
  } else {
    requestKey += (JSON.stringify(config.data) ?? '') + (JSON.stringify(config.params) ?? '')
  }
  return requestKey
}

export default instance
